import { defineStore } from 'pinia';
import { jwtDecode } from 'jwt-decode';
import axios from '@/axios.js';
import {ElMessage} from "element-plus";

export const useUserStore = defineStore('user', {
    state: () => ({
        userId: "",
        username: localStorage.getItem('token') ? jwtDecode(localStorage.getItem('token')).sub : null,
        rating: 0,
        playCount: 0,
        winCount: 0,
        winRate: 100,
    }),

    actions: {
        setUser(user) {
            this.userId = user.id;
            this.username = user.username;
            this.rating = user.rating;
            this.playCount = user.playCount;
            this.winCount = user.winCount;
            this.winRate = user.winRate;
            localStorage.setItem('userId', user.id);
        },

        clearUser() {
            this.userId = null;
            this.username = null;
            this.rating = 0;
            this.playCount = 0;
            this.winCount = 0;
            this.winRate = 100;
            localStorage.removeItem('userId');
        },


    },

    getters: {
        isLoggedIn: (state) => !!state.userId,
    },
    persist: {
        enabled: true, //Store中数据持久化生效
    },
});